<template>
  <div>
    <div id="amapcontainer"></div>
  </div>
</template>

<script>
import { defineComponent } from "vue";
import AMapLoader from "@amap/amap-jsapi-loader";
export default defineComponent({
  name: "mapDrag",
  data() {
    return {
      map: null,
      marker: null,
    };
  },
  props: {
    amapKey: {
      type: String,
      default: "8925c09ae1b631cb47968a82cad86513",
    },
    styleId: {
      type: String,
      default: "132b279b4b1863c69ecb11dcfd73093d",
    },
    name: {
      type: String,
      default: "武汉市江夏区万科红郡",
    },
    zoom: {
      type: Number,
      default: 12,
    },
    center: {
      type: [Array, String],
      default() {
        return [114.298572, 30.584355];
      },
    },
  },
  mounted() {
    this.initMap();
  },
  watch:{
    center(val){
        this.map.setZoomAndCenter(5,[val[0],val[1]]);
        this.map.setCenter([val[0],val[1]])
        this.map.setZoomAndCenter(14,[val[0],val[1]]);
        this.initMarker()
    }
  },
  methods: {
    initMap() {
      window._AMapSecurityConfig = {
        securityJsCode: "a54b939319e38dc4b61e718c49d99b52",
      };
      this.map = AMapLoader.load({
        key: '8925c09ae1b631cb47968a82cad86513',
        version: "2.0",
        AMapUI: {
          version: "1.1",
          plugins: [],
        },
      }).then((AMap) => {
          this.map = new AMap.Map("amapcontainer", {
            zoom: this.zoom, // 级别
            center: this.center, // 中心点坐标
            viewMode: "3D", // 是否为3D地图模式
            mapStyle: `amap://styles/132b279b4b1863c69ecb11dcfd73093d`,
            keyboardEnable: false,
            zoomEnable: true,
            dragEnable: true,
            animateEnable: true
          });
          this.initMarker()
          this.$emit("dragMap", this.map);
        })
        .catch((e) => {
          console.log(e);
        });
    },
    initMarker(){
        let icon = new AMap.Icon({
            size: new AMap.Size(20, 26),
            image: 'https://a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-default.png',
            imageSize: new AMap.Size(20, 26)
        });
        let infoWindow = new AMap.InfoWindow({
                anchor: 'bottom-right',
                content: this.name,
                offset: new AMap.Pixel(0, 0)
        });
        this.marker = new AMap.Marker({
           icon: icon,
           position: [this.center[0], this.center[1]], // 左边点的经纬度
           offset: new AMap.Pixel(0, -30) // 坐标点偏移量
         })
         this.marker.setMap(this.map)
         this.marker.on('click', (e) => {
             this.map.setCenter([e.lnglat.lng,e.lnglat.lat])
             infoWindow.open(this.map,[e.lnglat.lng,e.lnglat.lat]);
             this.map.setZoomAndCenter(14,e.target.getPosition());
        })
    },
  },
});
</script>

<style lang="scss" scoped>
#amapcontainer {
  width: 100%;
  //   height: 100%;
  height: calc(100vh);
  border-radius: 20px;
}
</style>
